﻿using LocalNas.Application.Service.Wallhaven.Dto;
using System.IO;

namespace LocalNas.Application.Service;

[ApiDescriptionSettings(ConstSwaggerGroup.NAS平台, Name = "壁纸服务", Order = 100)]
public class WallhavenService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysSetting> _sysSettingRep;
    public WallhavenService(SqlSugarRepository<SysSetting> sysSettingRep)
    {
        _sysSettingRep = sysSettingRep;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wallhaven/Search")]
    public async Task<SearchResult> Search(SearchRequest request)
    {
        var url = $"https://wallhaven.cc/api/v1/search?{HandleParam(request)}";
        var result = await url.GetAsAsync<SearchOutput>();


        //var web = new HtmlWeb();
        //var doc = await web.LoadFromWebAsync(url);
        //var cols = doc.DocumentNode.SelectNodes("//*[@id=\"thumbs\"]/section[1]/ul/li");
        //var totalPageText = doc.DocumentNode.SelectSingleNode("//*[@id=\"main\"]/header/h1").InnerText;
        //var pageNodes = doc.DocumentNode.SelectNodes("//ul[@class=\"pagination\"]/li/a");

        ////var totalItems = int.Parse(new Regex("^[1-9]\\d*").Match(totalPageText.Replace(",", "")).Value);
        //int.TryParse(pageNodes[pageNodes.Count - 2].InnerText, out int totalPage);
        //var list = cols.Select(x => new SearchResult.SearchResultItem
        //{
        //    Cover = x.SelectSingleNode("figure/img").Attributes["data-src"].Value,
        //    Suffix = x.SelectSingleNode("figure/div/span[@class=\"png\"]") == null ? "jpg" : "png",
        //    Href = x.SelectSingleNode("figure/a").Attributes["href"].Value,
        //    Title = x.SelectSingleNode("figure/div/span").InnerText,////*[@id="thumbs"]/section[1]/ul/li[1]/figure/div/span   doc.DocumentNode.SelectNodes("//ul[@class=\"pagination\"]/li/a")
        //}).ToList();

        return new SearchResult
        {
            TotalPage = result.meta.last_page,
            Items = result.data.Select(x => new SearchResult.SearchResultItem
            {
                Key = x.id,
                Cover = x.thumbs.large,
                Title = x.resolution,
                Image = x.path,
                Href = x.url,
                Name = $"{x.id}.{(x.file_type == "image/png" ? "png" : "jpg")}"
            }).ToList()
        };
    }

    ///// <summary>
    ///// 
    ///// </summary>
    ///// <param name="request"></param>
    ///// <returns></returns>
    //[HttpPost("/Wallhaven/Search2")]
    //public async Task<SearchResult> Search2(SearchRequest request)
    //{
    //    var url = $"https://wallhaven.cc/search?{HandleParam(request)}";

    //    var web = new HtmlWeb();
    //    var doc = await web.LoadFromWebAsync(url);
    //    var cols = doc.DocumentNode.SelectNodes("//*[@id=\"thumbs\"]/section[1]/ul/li");
    //    var totalPageText = doc.DocumentNode.SelectSingleNode("//*[@id=\"main\"]/header/h1").InnerText;
    //    var pageNodes = doc.DocumentNode.SelectNodes("//ul[@class=\"pagination\"]/li/a");

    //    //var totalItems = int.Parse(new Regex("^[1-9]\\d*").Match(totalPageText.Replace(",", "")).Value);
    //    int.TryParse(pageNodes[pageNodes.Count - 2].InnerText, out int totalPage);
    //    var list = cols.Select(x => new SearchResult.SearchResultItem
    //    {
    //        Cover = x.SelectSingleNode("figure/img").Attributes["data-src"].Value,
    //        Suffix = x.SelectSingleNode("figure/div/span[@class=\"png\"]") == null ? "jpg" : "png",
    //        Href = x.SelectSingleNode("figure/a").Attributes["href"].Value,
    //        Title = x.SelectSingleNode("figure/div/span").InnerText,////*[@id="thumbs"]/section[1]/ul/li[1]/figure/div/span   doc.DocumentNode.SelectNodes("//ul[@class=\"pagination\"]/li/a")
    //    }).ToList();

    //    return new SearchResult
    //    {
    //        TotalPage = totalPage,
    //        Items = list
    //    };
    //}


    private string HandleParam(SearchRequest request)
    {
        var paramStr = $"page={(request.Page > 0 ? request.Page : 1)}";
        if (!string.IsNullOrWhiteSpace(request.Q))
        {
            paramStr += $"&q={request.Q}";
        }
        if (!string.IsNullOrWhiteSpace(request.Categories))
        {
            paramStr += $"&categories={request.Categories}";
        }
        if (!string.IsNullOrWhiteSpace(request.Purity))
        {
            paramStr += $"&purity={request.Purity}";
        }
        if (!string.IsNullOrWhiteSpace(request.Atleast))
        {
            paramStr += $"&atleast={request.Atleast}";
        }
        if (!string.IsNullOrWhiteSpace(request.Ratios))
        {
            paramStr += $"&ratios={request.Ratios}";
        }
        if (!string.IsNullOrWhiteSpace(request.Sorting))
        {
            paramStr += $"&sorting={request.Sorting}";
        }
        if (!string.IsNullOrWhiteSpace(request.Order))
        {
            paramStr += $"&order={request.Order}";
        }
        if (!string.IsNullOrWhiteSpace(request.Colors))
        {
            paramStr += $"&colors={request.Colors}";
        }
        if (!string.IsNullOrWhiteSpace(request.TopRange))
        {
            paramStr += $"&topRange={request.TopRange}";
        }
        if (!string.IsNullOrWhiteSpace(request.Resolutions))
        {
            paramStr += $"&resolutions={request.Resolutions}";
        }

        if (!string.IsNullOrWhiteSpace(request.ApiKey))
        {
            paramStr += $"&apikey={request.ApiKey}";
        }

        return paramStr;
    }

    /// <summary>
    /// 下载壁纸
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    [HttpGet("/Wallhaven/Download")]
    public async Task<string> Download(string url)
    {
        var setting = await _sysSettingRep.GetFirstAsync(x => x.Key == ConstSettingKey.壁纸下载目录);
        if (setting == null || string.IsNullOrWhiteSpace(setting.Value)) throw Oops.Oh("请先设置【壁纸下载目录】");
        if (!Directory.Exists(setting.Value)) Directory.CreateDirectory(setting.Value);
        var result = await url.GetAsStreamAsync();
        var fileName = new Regex("(?<=wallhaven-).*?$").Match(url).Value;
        var _path = Path.Combine(setting.Value, fileName);
        using (var fileStream = File.Create(_path))
        {
            await result.Stream.CopyToAsync(fileStream);
        }
        return _path;
    }
}
